package br.com.fiap.telas;

import br.com.fiap.arquivo.MyNode;
import br.com.fiap.servicos.BasicDirectedGraph;

import javax.swing.*;

/**
 * Created with IntelliJ IDEA.
 * User: gabriel.medina
 * Date: 29/10/12
 * Time: 14:45
 * To change this template use File | Settings | File Templates.
 */
public class Entrada extends javax.swing.JFrame {

    BasicDirectedGraph graph = new BasicDirectedGraph();

    /**
     * Creates new form Entrada
     */
    public Entrada() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        ImageIcon img = new ImageIcon("src/imagens/Fiap2.jpeg");
        ImageIcon imgIcon = new ImageIcon("src/imagens/fiap.gif");
        this.setIconImage(imgIcon.getImage());
        this.setTitle("Rede Social - Grafos");

        jPanel1 = new javax.swing.JPanel();
        jpGrafo = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtLog = new javax.swing.JTextArea();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        bntCalcular = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        txtPartida = new javax.swing.JTextField();
        txtDestino = new javax.swing.JTextField();
        txtDistancia = new javax.swing.JTextField();
        cbCalculo = new javax.swing.JComboBox();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();


        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout jpGrafoLayout = new javax.swing.GroupLayout(jpGrafo);

        jpGrafo.setLayout(jpGrafoLayout);
        jpGrafoLayout.setHorizontalGroup(
                jpGrafoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGap(0, 0, Short.MAX_VALUE)
        );
        jpGrafoLayout.setVerticalGroup(
                jpGrafoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGap(0, 475, Short.MAX_VALUE)
        );

        jPanel5.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Logs"));
        jPanel4.setAutoscrolls(true);

        txtLog.setColumns(20);
        txtLog.setRows(5);
        txtLog.setEnabled(false);
        txtDistancia.setEnabled(false);
        txtDistancia.setToolTipText("Somente Números");
        txtPartida.setToolTipText("Ex: RM62150");
        txtDestino.setToolTipText("Ex: RM62470");

        jScrollPane1.setViewportView(txtLog);

        graph = new BasicDirectedGraph();
        jpGrafo = graph.constructGraph();

        jpGrafo.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
                jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 552, Short.MAX_VALUE)
        );
        jPanel4Layout.setVerticalGroup(
                jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane1)
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Cálculo"));

        jLabel1.setText("Partida: ");
        jLabel2.setText("Destino: ");

        bntCalcular.setText("Calcular");
        bntCalcular.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bntCalcularActionPerformed(evt);
            }
        });

        jLabel3.setText("Distância: ");
        cbCalculo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Menor Caminho", "Alunos Incomunicáveis", "Alunos Intermediários", "Fluxo Máximo de Alunos" }));
        cbCalculo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbCalculoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel2Layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(cbCalculo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addGroup(jPanel2Layout.createSequentialGroup()
                                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                        .addComponent(jLabel1)
                                                        .addComponent(jLabel2))
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                        .addComponent(txtDestino)
                                                        .addComponent(txtPartida)))
                                        .addGroup(jPanel2Layout.createSequentialGroup()
                                                .addComponent(jLabel3)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(txtDistancia, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                .addComponent(bntCalcular)))
                                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel2Layout.createSequentialGroup()
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(jLabel1)
                                        .addComponent(txtPartida, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(jLabel2)
                                        .addComponent(txtDestino, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cbCalculo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(bntCalcular)
                                        .addComponent(jLabel3)
                                        .addComponent(txtDistancia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
                jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel5Layout.createSequentialGroup()
                                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel5Layout.setVerticalGroup(
                jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jpGrafo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jpGrafo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        jMenu1.setText("About");
        jMenuItem1.setText("Info");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });

        jMenu1.add(jMenuItem1);
        jMenuBar1.add(jMenu1);
        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        pack();
    }// </editor-fold>

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
        new Info();
    }


    public boolean compString(){

        int compare = txtDestino.getText().compareToIgnoreCase(txtPartida.getText());
        if(compare < 0){
            return true;
        }
        txtLog.setText("Os campos Partida e Destino devem ser diferentes.");
        txtLog.setEnabled(false);
        return false;
    }

    public boolean validaRM(String texto){

        Integer num, numDist;
        StringBuilder sb = new StringBuilder();

        if(txtDistancia.isEnabled()){
            try{
                numDist = Integer.parseInt(txtDistancia.getText());

            }catch (NumberFormatException ex){
                sb.append("O campo 'Distância' deve ser preenchido com numeros inteiros."+"\n");
            }
        }


        if(!texto.equals("")){
            if(texto.substring(0,2).compareToIgnoreCase("RM") == 0){

                try{
                    String aux = texto.substring(2,7);
                    num = Integer.parseInt(aux);
                    return true;
                }
                catch (StringIndexOutOfBoundsException ex){
                    sb.append("Os campos de cálculo devem seguir o formato: RM12345"+"\n");
                }
                catch (NumberFormatException ex){
                    sb.append("Os campos de cálculo devem seguir o formato: RM12345"+"\n");
                }

                txtLog.setText(sb.toString());
                txtLog.setEnabled(false);
                return false;
            }
            else{
                sb.append("Os campos Partida e Destino devem seguir o formato: RM12345"+"\n");
                txtLog.setEnabled(false);
                txtLog.setText(sb.toString());
                return false;
            }
        }
        else {
            sb.append("Os campos de cálculo precisam ser preechidos."+"\n");
            txtLog.setEnabled(false);
            txtLog.setText(sb.toString());
        }
        return false;
    }


    private void bntCalcularActionPerformed(java.awt.event.ActionEvent evt) {

        MyNode n1, n2;
        n1 = new MyNode();
        n2 = new MyNode();
        n1.setId(txtPartida.getText().toUpperCase());
        n2.setId(txtDestino.getText().toUpperCase());

        if(cbCalculo.getSelectedIndex() == 0){
            if((validaRM(n1.getId()) && validaRM(n2.getId())) && compString()) {
                graph.calcUnweightedShortestPath(n1,n2);
                atualizaLog();
            }
        }

        if(cbCalculo.getSelectedIndex() == 1){
                graph.calcAlunoIncomunicaveis(n1);
                atualizaLog();
        }


        if(cbCalculo.getSelectedIndex() == 2){
            if((validaRM(n1.getId()) && validaRM(n2.getId())) && compString()){
                graph.calcMaxFlow(n1,n2);
                atualizaLog();
            }
        }

        if(cbCalculo.getSelectedIndex() == 3){
           if(validaRM(n1.getId())){
               Integer distancia = Integer.parseInt(txtDistancia.getText());
               graph.calcDistancia(n1, distancia);
               atualizaLog();
           }
        }
    }

    public void atualizaLog(){

        StringBuilder stringBuilder = new StringBuilder();

        for(String msg : graph.getListMessage()){

            stringBuilder.append(msg);
            stringBuilder.append("\n");
        }
        txtLog.setText(stringBuilder.toString());
        txtLog.setEnabled(true);
    }

    private void cbCalculoActionPerformed(java.awt.event.ActionEvent evt) {

        if(cbCalculo.getSelectedItem().equals("Menor Caminho")){
            txtDistancia.setEnabled(false);
            txtDestino.setEnabled(true);
        }

        if(cbCalculo.getSelectedItem().equals("Alunos Incomunicáveis")){
            txtDestino.setEnabled(false);
            txtDistancia.setEnabled(false);
        }

        if(cbCalculo.getSelectedItem().equals("Alunos Intermediários")){
            txtDestino.setEnabled(true);
            txtDistancia.setEnabled(false);
        }

        if(cbCalculo.getSelectedItem().equals("Fluxo Máximo de Alunos")){
            txtDistancia.setEnabled(true);
            txtDestino.setEnabled(false);
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */

        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Entrada.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Entrada.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Entrada.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Entrada.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Entrada().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton bntCalcular;
    private javax.swing.JComboBox cbCalculo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel jpGrafo;
    private javax.swing.JTextField txtDestino;
    private javax.swing.JTextField txtDistancia;
    private javax.swing.JTextArea txtLog;
    private javax.swing.JTextField txtPartida;
    // End of variables declaration
}